package com.iring.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.iring.domain.common.User;
import com.iring.exception.ParamInvalidException;
import com.iring.exception.config.ErrorEnum;
import com.iring.interceptor.UserInterceptor;
import com.iring.util.common.StringUtil;
import com.iring.vo.common.BooleanResultVO;
import com.iring.vo.common.ResultVO;
import com.iring.vo.user.LoginVO;

/**
 * @author wanggan
 */
@RestController
public class LoginController extends BaseController {

    /**
     * 登陆，验证用户名和密码的匹配，当用户信息匹配时将用户信息放入到session中
     *
     * @param loginVO
     *            {@link LoginVO}用户名和密码
     * @return 登陆成功返回用户名
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResultVO login(@RequestBody LoginVO loginVO) {
        User user = userService.findUser(loginVO);
        String ip= getUserRealIp();
        if( user instanceof  User) {
            reSetUserSession(user);
            // 处理是否存在有未处理的异常情况
            String username = user.getUsername();
            logService.saveLog(username, "login",ip , true);
            userService.dealAmoutTask(username,ip);
            return new ResultVO(username);
        }else{
            logService.saveLog(loginVO.getUsername(), "login", ip, false,"username or password error");
            throw new ParamInvalidException(ErrorEnum.USERNAME_OR_PASSWORD_ERROR);
        }
    }

    /**
     * 退出登录 清空session
     *
     * @param request
     *            request对象
     * @return 返回成功
     */
    @RequestMapping(value = "/loginout", method = RequestMethod.POST)
    public BooleanResultVO loginout(HttpServletRequest request) {
        logService.saveLog(getUserSession().getUsername(),"logout",getUserRealIp(),true);
        request.getSession().removeAttribute(UserInterceptor.SESSION_USER);

        return new BooleanResultVO(Boolean.TRUE);
    }

    @RequestMapping(value = "/get-token", method = RequestMethod.GET)
    public ResultVO getToken(HttpServletRequest request) {
        HttpSession session = request.getSession(true);
        Object object = session.getAttribute(ACCESS_TOKEN);
        if (object == null) {
            // 如果token不存在,则重新生成,并放到session中
            String token = String.valueOf(System.currentTimeMillis()) + StringUtil.getRandomString(32);
            session.setAttribute(ACCESS_TOKEN, token);
            object = token;
        }
        return new ResultVO(object);
    }
}
